/*
 * @Author: 徐军
 * @Date: 2021-05-20 17:35:35
 * @Last Modified by: 徐军
 * @Last Modified time: 2021-05-25 09:52:48
 * 创建类
 */
const Inquirer = require("inquirer");
const downloadGitRepo = require('download-git-repo');// 可以根据项目名和tag 拉去仓库，不支持promise
const {wrapLoading} = require('./utils');
const { fetchRepoList,fetchRepoTagList } = require("./request");
const util = require('util') // node自带
const path = require('path');
const {bigText}=require('./welcome');
const {clone1,clone2,clone3} = require('./clone');
class Creator {
  constructor(projectName, targetDir) {
    this.name = projectName;
    this.target = targetDir;
    // 手动转换成promise方法
    this.downloadGitRepo = util.promisify(downloadGitRepo);
  }

  async fethchRepo() {
    // 失败重新获取
    let repos = await wrapLoading(fetchRepoList, "下载模版中。。");
    if (!repos) return;
    let reposName = repos.map((item) => item.name);
    let { repo } = await Inquirer.prompt({
      name: "repo",
      type: "list",
      choices: reposName,
      message: "请选择一个模版",
    });
    return repo;
  }
  async fetchTag(repo) {
    let tags = await wrapLoading(fetchRepoTagList,'获取tag列表中。。。',repo)
    if(!tags) return;
    let tagsName = tags.map(item=>item.name)
    let { tag } = await Inquirer.prompt({
        name: "tag",
        type: "list",
        choices: tagsName,
        message: "请选择一个tag",
      });
      return tag;
  }
  async download(repo,tag) {
      /**
       * 拼接出下载路径 zhu-cli/vue-template#1.0
       * 下载资源到指定路径(后续增加缓存功能,应该下载到系统目录中，稍后可以在使用ejs hadlerbar去渲染模版最后生成结果再写入)
      */
    let requestUrl = `zhu-cli/${repo}${tag?'#'+tag:''}`
    await this.downloadGitRepo(requestUrl,path.resolve(process.cwd(),`${repo}@${tag}`))
    return this.target;
  }

  // 通过api 获取组织下所有到库供用户选择
  async create() {
    // 1、拉取当前组织下模版
    let repo = await this.fethchRepo();
    // 2、通过模版找到版本号
    let tag = await this.fetchTag(repo);
    // 3、1）获取到下载地址并下载（通过github api 进行下载库）
    let downloadUrl = await this.download(repo,tag);
    // 4、下载依赖

    // 5、编译模版


    // 6、欢迎界面
    bigText('jun Welcome')
  }


  // 直接使用库地址clone
  async createDirect(){
    // clone1()
    // clone2()
    clone3(this.name)
  }
}
module.exports = Creator;
